﻿using Mr.Common;
using Mr.Common.Enum;
using Mr.Common.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TestSqlSurging.Controllers
{
    public class BaseController : Controller
    {
        public string userName;
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            
            //过滤包含有未登录可访问属性
            if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any())
            {
                return;
            }
            var request = filterContext.HttpContext.Request;
            //获取token获取
            var token = request.Headers["UserToken"];
            if(string.IsNullOrEmpty(token))
            {
                //尝试从cookies中获取                
                if(request.Cookies["UserToken"]!=null)
                {
                    token = request.Cookies["UserToken"].Value;
                }
            }
            var validateResult = false;
            //验证token
            if(!string.IsNullOrEmpty(token))
            {
                validateResult = TokenManager.Validate(token, payLoad =>
                {
                    var success = true;
                    success = success && payLoad["aud"]?.ToString() == "user";
                    if(success)
                    {
                        userName = payLoad["user"].ToString();
                    }
                    return success;
                });
            }
            if(!validateResult || string.IsNullOrEmpty(userName))
            {
                if (HttpRequestExtension.IsAjaxRequest(request))
                {
                    var result = new JsonResult();
                    result.ContentType = "text/json";
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    result.Data = new Mr.Common.AjaxResult(ResultStatus.NotLogin, "当前未登录");
                    filterContext.Result = result;
                    return;
                }
                else
                {
                    Response.Redirect("/Login");
                    filterContext.Result = new EmptyResult();
                    return;
                }
            }
        }
    }
}